﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JMailT.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace JMailT.Store
{
    public class LocalStore
    {
        public string User { get; set; }
        public string Provider { get; set; }

        public Mail Load(string provider, string user, LiteItem item)
        {
            string dir = string.Format(@"c:\JMT\{0}\{1}\", provider, user);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string path = string.Format(@"c:\JMT\{0}\{1}\{2}.jm", provider, user, item.UniqueID);
            if (!File.Exists(path))
            {
                return null;
            }

            BinaryFormatter formatter = new BinaryFormatter();
            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                object obj = formatter.Deserialize(stream);
                if (obj != null)
                {
                    return obj as Mail;
                }
            }
            return null;
        }

        public void Save(string provider, string user, Mail mail)
        {
            string dir = string.Format(@"c:\JMT\{0}\{1}\", provider, user);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string path = string.Format(@"c:\JMT\{0}\{1}\{2}.jm", provider, user, mail.UniqueID);
            if (!File.Exists(path))
            {
                using (FileStream stream = new FileStream(path, FileMode.CreateNew))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, mail);
                }
            }
        }
    }
}
